package com.dragon.mmochat.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcDaoSupport;

import com.dragon.mmochat.model.MmochatEventLog;
import com.dragon.mmochat.model.enumType.MmochatEventType;

public class MmochatEventDao extends SimpleJdbcDaoSupport {
	private static final EventLogMapper eventMapper = new EventLogMapper();

	// 增加事件记录
	private static final String addEventLogSql = "insert into event_log(type, time, title, content) "
			+ "values(?, ?, ?, ?)";

	public void addEventLog(int type, long time, String title, String content) {
		getSimpleJdbcTemplate().update(addEventLogSql, type, time, title,
				content);
	}

	// 读取事件记录
	private static final String getEventLogSql = "select * from event_log "
			+ "where type = ? and time > ? and time < ?";

	public List<MmochatEventLog> getEventLog(int type, long startTime,
			long endTime) {
		return getSimpleJdbcTemplate().query(getEventLogSql, eventMapper, type,
				startTime, endTime);
	}

	// 读取所有事件记录
	private static final String getAllEventLogSql = "select * from event_log where time > ?";

	public List<MmochatEventLog> getAllEventLog(long startTime) {
		return getSimpleJdbcTemplate().query(getAllEventLogSql, eventMapper,
				startTime);
	}

	static class EventLogMapper implements
			ParameterizedRowMapper<MmochatEventLog> {
		@Override
		public MmochatEventLog mapRow(ResultSet rs, int rowNum)
				throws SQLException {
			MmochatEventLog eventLog = new MmochatEventLog();
			eventLog.setId(rs.getInt("id"));
			eventLog.setType(MmochatEventType.get(rs.getInt("type")));
			eventLog.setTime(rs.getLong("time"));
			eventLog.setTitle(rs.getString("title"));
			eventLog.setContent(rs.getString("content"));

			return eventLog;
		}
	}
}
